<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h2 class="page-title">
            <el-icon class="title-icon"><Goods /></el-icon>
            农产品管理
          </h2>
          <p class="page-description">管理平台上的所有农产品信息</p>
        </div>
        <div class="header-right">
          <div class="header-stats">
            <div class="stat-item">
              <div class="stat-value">{{ totalCount }}</div>
              <div class="stat-label">总商品数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ onlineCount }}</div>
              <div class="stat-label">在售商品</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <el-card class="content-container" shadow="never">
      <!-- 工具栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button
            type="primary"
            @click="handleAdd"
            size="large"
            class="add-btn"
          >
            <el-icon><Plus /></el-icon>
            新增农产品
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
            size="large"
            plain
          >
            <el-icon><Delete /></el-icon>
            批量删除 ({{ selectedRows.length }})
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-button @click="handleRefresh" size="large" circle>
            <el-icon><Refresh /></el-icon>
          </el-button>
        </div>
      </div>

      <!-- 搜索区域 -->
      <el-card class="search-card" shadow="hover">
        <template #header>
          <div class="search-header">
            <el-icon><Search /></el-icon>
            <span>筛选条件</span>
            <el-button
              type="text"
              @click="toggleSearchForm"
              class="toggle-btn"
            >
              {{ searchFormVisible ? '收起' : '展开' }}
              <el-icon>
                <ArrowUp v-if="searchFormVisible" />
                <ArrowDown v-else />
              </el-icon>
            </el-button>
          </div>
        </template>

        <el-collapse-transition>
          <div v-show="searchFormVisible">
            <el-form :model="searchForm" class="search-form" :inline="true">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="产品名称">
                    <el-input
                      v-model="searchForm.nongchanpinName"
                      placeholder="请输入产品名称"
                      clearable
                      :prefix-icon="Search"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="产品分类">
                    <el-select
                      v-model="searchForm.nongchanpinTypes"
                      placeholder="请选择分类"
                      clearable
                      style="width: 100%"
                    >
                      <el-option label="🥬 蔬菜" value="1" />
                      <el-option label="🍎 水果" value="2" />
                      <el-option label="🌾 粮食" value="3" />
                      <el-option label="🥩 肉类" value="4" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="价格范围">
                    <el-input
                      v-model="searchForm.minPrice"
                      placeholder="最低价格"
                      type="number"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="　">
                    <el-input
                      v-model="searchForm.maxPrice"
                      placeholder="最高价格"
                      type="number"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24" class="search-actions">
                  <el-button type="primary" @click="handleSearch" size="large">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="handleReset" size="large">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-transition>
      </el-card>

      <!-- 数据表格 -->
      <div class="table-container">
        <el-table
          :data="tableData"
          style="width: 100%"
          v-loading="loading"
          @selection-change="(rows)=>selectedRows=rows"
          class="modern-table"
          :header-cell-style="{ background: '#f8f9fa', color: '#606266', fontWeight: '600' }"
          stripe
        >
          <el-table-column type="selection" width="50" />

          <el-table-column prop="id" label="ID" width="80" align="center">
            <template #default="scope">
              <el-tag size="small" type="info">#{{ scope.row.id }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="产品信息" min-width="300">
            <template #default="scope">
              <div class="product-info">
                <div class="product-image">
                  <el-image
                    style="width: 60px; height: 60px; border-radius: 8px;"
                    :src="scope.row.nongchanpinPhoto"
                    :preview-src-list="[scope.row.nongchanpinPhoto]"
                    fit="cover"
                    :preview-teleported="true"
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </div>
                <div class="product-details">
                  <div class="product-name">{{ scope.row.nongchanpinName }}</div>
                  <div class="product-desc">{{ scope.row.nongchanpinContent || '暂无描述' }}</div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="nongchanpinValue" label="分类" width="120" align="center">
            <template #default="scope">
              <el-tag
                :type="getCategoryTagType(scope.row.nongchanpinTypes)"
                effect="light"
              >
                {{ getCategoryIcon(scope.row.nongchanpinTypes) }} {{ scope.row.nongchanpinValue }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="价格信息" width="150" align="center">
            <template #default="scope">
              <div class="price-info">
                <div class="current-price">¥{{ scope.row.nongchanpinNewMoney }}</div>
                <div v-if="scope.row.nongchanpinOldMoney && scope.row.nongchanpinOldMoney > scope.row.nongchanpinNewMoney"
                     class="old-price">
                  ¥{{ scope.row.nongchanpinOldMoney }}
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="nongchanpinKucunNumber" label="库存" width="100" align="center">
            <template #default="scope">
              <el-tag
                :type="getStockTagType(scope.row.nongchanpinKucunNumber)"
                effect="light"
              >
                {{ scope.row.nongchanpinKucunNumber }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="shangjiaName" label="商家" width="120" align="center">
            <template #default="scope">
              <div class="merchant-info">
                <el-icon><Shop /></el-icon>
                <span>{{ scope.row.shangjiaName || '未知商家' }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="状态" width="100" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.shangxiaTypes"
                :active-value="1"
                :inactive-value="2"
                active-text="上架"
                inactive-text="下架"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" width="180" align="center">
            <template #default="scope">
              <div class="time-info">
                <el-icon><Clock /></el-icon>
                <span>{{ formatTime(scope.row.createTime) }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleEdit(scope.row)"
                  link
                >
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button
                  type="info"
                  size="small"
                  @click="handleView(scope.row)"
                  link
                >
                  <el-icon><View /></el-icon>
                  查看
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row)"
                  link
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
          />
        </div>
      </div>

      <!-- 新增/编辑对话框 -->
      <el-dialog v-model="dialog.visible" :title="dialog.title" width="680px" @close="handleDialogClose">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="产品名称" prop="nongchanpinName">
            <el-input v-model="form.nongchanpinName" placeholder="请输入产品名称" />
          </el-form-item>
          <el-form-item label="产品分类" prop="nongchanpinTypes">
            <el-select v-model="form.nongchanpinTypes" placeholder="请选择分类">
              <el-option label="蔬菜" :value="1" />
              <el-option label="水果" :value="2" />
              <el-option label="粮食" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="产品图片" prop="nongchanpinPhoto">
            <ImageUpload v-model="form.nongchanpinPhoto" />
          </el-form-item>
          <el-form-item label="销售价格" prop="nongchanpinNewMoney">
            <el-input type="number" v-model.number="form.nongchanpinNewMoney" placeholder="请输入价格" />
          </el-form-item>
          <el-form-item label="库存数量" prop="nongchanpinKucunNumber">
            <el-input type="number" v-model.number="form.nongchanpinKucunNumber" placeholder="请输入库存数量" />
          </el-form-item>
          <el-form-item label="商家ID" prop="shangjiaId">
            <el-input v-model="form.shangjiaId" placeholder="可选，如有联动下拉可后续接入" />
          </el-form-item>
          <el-form-item label="产品描述" prop="nongchanpinContent">
            <el-input v-model="form.nongchanpinContent" type="textarea" :rows="4" placeholder="请输入产品描述" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialog.visible=false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>


      <!-- 分页 -->
      <el-pagination
        :current-page="pagination.page"
        :page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right;"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Delete,
  Edit,
  View,
  Search,
  Refresh,
  Goods,
  Shop,
  Clock,
  Picture,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'
import ImageUpload from '@/components/ImageUpload.vue'

// 取全局 http 实例
const { proxy } = getCurrentInstance()
const http = proxy.$http

// 响应式数据
const loading = ref(false)
const tableData = ref([])
let selectedRows = ref([])
const searchFormVisible = ref(true)

// 统计数据
const totalCount = computed(() => tableData.value.length)
const onlineCount = computed(() => tableData.value.filter(item => item.shangxiaTypes === 1).length)

// 新增/编辑 对话框与表单
const dialog = reactive({ visible: false, isEdit: false, title: '新增农产品' })
const formRef = ref()
const form = reactive({
  id: null,
  nongchanpinName: '',
  nongchanpinTypes: '',
  nongchanpinPhoto: '',
  nongchanpinNewMoney: null,
  nongchanpinKucunNumber: null,
  shangjiaId: '',
  nongchanpinContent: ''
})
const rules = {
  nongchanpinName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  nongchanpinTypes: [{ required: true, message: '请选择分类', trigger: 'change' }],
  nongchanpinNewMoney: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  nongchanpinKucunNumber: [{ required: true, message: '请输入库存数量', trigger: 'blur' }]
}

const searchForm = reactive({
  nongchanpinName: '',
  nongchanpinTypes: '',
  minPrice: '',
  maxPrice: ''
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 工具方法
const getCategoryIcon = (type) => {
  const icons = {
    1: '🥬',
    2: '🍎',
    3: '🌾',
    4: '🥩'
  }
  return icons[type] || '📦'
}

const getCategoryTagType = (type) => {
  const types = {
    1: 'success',
    2: 'warning',
    3: 'info',
    4: 'danger'
  }
  return types[type] || ''
}

const getStockTagType = (stock) => {
  if (stock <= 0) return 'danger'
  if (stock <= 10) return 'warning'
  return 'success'
}

const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

const toggleSearchForm = () => {
  searchFormVisible.value = !searchFormVisible.value
}



// 方法
const loadData = async () => {
  loading.value = true

  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    }

    // 处理价格范围
    if (searchForm.minPrice) {
      params.minPrice = searchForm.minPrice
    }
    if (searchForm.maxPrice) {
      params.maxPrice = searchForm.maxPrice
    }

    console.log('加载农产品数据，参数:', params)

    const response = await http({
      url: '/nongchanpin/page',
      method: 'get',
      params: params
    })

    console.log('农产品数据响应:', response)

    if (response.code === 0) {
      tableData.value = response.data.list || []
      total.value = response.data.total || 0

      // 处理图片URL
      tableData.value.forEach(item => {
        if (item.nongchanpinPhoto && !item.nongchanpinPhoto.startsWith('http')) {
          item.nongchanpinPhoto = `http://localhost:8080/lelenongchanpinxiaoshou/${item.nongchanpinPhoto}`
        }
      })
    } else {
      ElMessage.error(response.msg || '加载数据失败')
    }
  } catch (error) {
    console.error('加载农产品数据失败:', error)
    ElMessage.error('加载数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}


const handleDialogClose = () => {
  formRef.value && formRef.value.clearValidate()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  try {
    const api = dialog.isEdit ? '/nongchanpin/update' : '/nongchanpin/save'
    const payload = { ...form }
    const res = await http({ url: api, method: 'post', data: payload })
    if (res.code === 0) {
      ElMessage.success(dialog.isEdit ? '更新成功' : '新增成功')
      dialog.visible = false
      loadData()
    } else {
      ElMessage.error(res.msg || '提交失败')
    }
  } catch (e) {
    console.error('提交失败', e)
    ElMessage.error('提交失败')
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

const handleRefresh = () => {
  loadData()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadData()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadData()
}

const handleView = (row) => {
  // 跳转到详情页面或打开详情对话框
  console.log('查看商品:', row)
}

const handleStatusChange = async (row) => {
  try {
    const response = await http({
      url: '/nongchanpin/update',
      method: 'post',
      data: row
    })

    if (response.code === 0) {
      ElMessage.success('状态更新成功')
    } else {
      ElMessage.error(response.msg || '状态更新失败')
      // 恢复原状态
      row.shangxiaTypes = row.shangxiaTypes === 1 ? 2 : 1
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
    // 恢复原状态
    row.shangxiaTypes = row.shangxiaTypes === 1 ? 2 : 1
  }
}

const handleAdd = () => {
  dialog.title = '新增农产品'
  dialog.isEdit = false
  Object.assign(form, { id: null, nongchanpinName: '', nongchanpinTypes: '', nongchanpinPhoto: '', nongchanpinNewMoney: null, nongchanpinKucunNumber: null, shangjiaId: '', nongchanpinContent: '' })
  dialog.visible = true
}

const handleEdit = (row) => {
  dialog.title = '编辑农产品'
  dialog.isEdit = true
  Object.assign(form, { ...row })
  dialog.visible = true
}

const handleBatchDelete = async () => {
  if (!selectedRows.value || selectedRows.value.length === 0) return
  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '批量删除',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    const ids = selectedRows.value.map(r => r.id)
    const res = await http({ url: '/nongchanpin/delete', method: 'post', data: { ids } })
    if (res.code === 0) {
      ElMessage.success('批量删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '批量删除失败')
    }
  } catch (e) {
    if (e !== 'cancel') {
      console.error('批量删除失败', e)
      ElMessage.error('批量删除失败')
    }
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除农产品"${row.nongchanpinName}"吗？`,
      '确认删除',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    const res = await http({ url: '/nongchanpin/delete', method: 'post', data: { ids: [row.id] } })
    if (res.code === 0) {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (e) {
    if (e !== 'cancel') {
      console.error('删除农产品失败', e)
      ElMessage.error('删除失败')
    }
  }
}



// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
@import '@/styles/index.scss';

.page-container {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

/* 页面头部 */
.page-header {
  background: white;
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  flex: 1;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.title-icon {
  font-size: 28px;
  color: #409eff;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-stats {
  display: flex;
  gap: 32px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
  line-height: 1;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 内容容器 */
.content-container {
  border-radius: 16px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.content-container :deep(.el-card__body) {
  padding: 24px;
}

/* 工具栏 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.toolbar-left {
  display: flex;
  gap: 12px;
}

.add-btn {
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  border: none;
  border-radius: 8px;
  font-weight: 500;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 24px;
  border-radius: 12px;
  border: none;
}

.search-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #606266;
}

.toggle-btn {
  margin-left: auto;
  color: #409eff;
}

.search-form {
  margin-top: 16px;
}

.search-actions {
  text-align: right;
  margin-top: 16px;
}

/* 表格容器 */
.table-container {
  background: white;
  border-radius: 12px;
  overflow: hidden;
}

.modern-table {
  border-radius: 12px;
}

.modern-table :deep(.el-table__header) {
  background: #f8f9fa;
}

.modern-table :deep(.el-table th) {
  background: #f8f9fa;
  border-bottom: 2px solid #e4e7ed;
  font-weight: 600;
  color: #606266;
}

.modern-table :deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 0;
}

/* 产品信息 */
.product-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.product-image {
  flex-shrink: 0;
}

.image-error {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  background: #f5f7fa;
  border-radius: 8px;
  color: #c0c4cc;
}

.product-details {
  flex: 1;
  min-width: 0;
}

.product-name {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  line-height: 1.4;
}

.product-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 价格信息 */
.price-info {
  text-align: center;
}

.current-price {
  font-size: 16px;
  font-weight: 600;
  color: #f56c6c;
  display: block;
}

.old-price {
  font-size: 12px;
  color: #c0c4cc;
  text-decoration: line-through;
  margin-top: 2px;
}

/* 商家信息 */
.merchant-info {
  display: flex;
  align-items: center;
  gap: 6px;
  justify-content: center;
  font-size: 14px;
  color: #606266;
}

/* 时间信息 */
.time-info {
  display: flex;
  align-items: center;
  gap: 6px;
  justify-content: center;
  font-size: 12px;
  color: #909399;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }

  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .header-stats {
    gap: 16px;
  }

  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .search-form :deep(.el-form-item) {
    margin-bottom: 16px;
  }

  .modern-table :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }
}
</style>
